package com.weibo.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.weibo.entity.WeiboToken;
import com.weibo.service.WeiboService;
import com.weibo.util.WeiboHelper;

public class WeiboZhuanfaServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		doPost(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		String isPinglunStr = request.getParameter("isPinglun");//选中的参数值是on
		String weiboURL = request.getParameter("weiboURL");
		String isZhuanfaStr = request.getParameter("isZhuanfa");
		String text = request.getParameter("text");
		String zhanghaoids[] = request.getParameterValues("zhanghaoids");
		String timeStr = request.getParameter("timeStr");
		String mid = "";//需要转发的微博ID
		
		WeiboService ws = new WeiboService();
		
		int isZhuanfa = 0;
		System.out.println("isZhuanfaStr:"+isZhuanfaStr);
		if(isZhuanfaStr != null){
			 isZhuanfa =  Integer.parseInt(isZhuanfaStr);
		}
		int isPinglun = 0;
		if(isPinglunStr!=null&"on".equals(isPinglunStr)){
			isPinglun = 1;
		}
		List<WeiboToken> wts = ws.findAllToken();
		if(isZhuanfa == 0){
			request.setAttribute("wts", wts);
			request.getRequestDispatcher("/weibo_zhuanfa.jsp").forward(request, response);
		}else{
			request.setAttribute("wts", wts);
			//WeiboZhuanfaService.zhuanfa(id, texts, wts, isPinglun);
			//处理URL
			if(weiboURL != null){
				String urls[] = weiboURL.split("/");
				String urlStr = urls[urls.length-1];
				 mid = WeiboHelper.url2mid(urlStr);
				 System.out.println("mid:"+mid);
			}
			//处理转发语
			if(text != null && zhanghaoids != null){
				//处理时间间隔
				Long tl = Long.parseLong(timeStr);
				
				//字符转数组转化为整数数组
				for(int j = 0;j<zhanghaoids.length;j++){
					System.out.println("===========zhanghaoids:["+zhanghaoids[j]+"]");
				}

				Long ids[] =new Long[zhanghaoids.length];
				for(int i = 0; i < zhanghaoids.length; i++){
					ids[i]= Long.parseLong(zhanghaoids[i]);
				}
				//根据ids获得微博的授权列表
				List< WeiboToken> ts = ws.findTokenByids(ids);
				String texts[] = text.split("\r");
				ws.zhuanfa(mid, texts, ts, isPinglun,tl);
				request.setAttribute("success", "任务执行成功！！！");
				request.getRequestDispatcher("/weibo_zhuanfa.jsp").forward(request, response);
			}
		
	}
		}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
